package knowlwdge_graph.knowledge_etl.entity_etl;

import knowlwdge_graph.knowledge_etl.yago_etl.*;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by julianzliu on 4/24/2017.
 */
public class EntityExtractor {

    static final org.slf4j.Logger logger = LoggerFactory.getLogger(EntityExtractor.class);

    private ExtractorPostgres extractorPostgres;
    private EntityPostgres entityPostgres;
    private LoderOrientDB loderOrientDB;

    public EntityExtractor(){
        this.extractorPostgres = new ExtractorPostgres();
        this.loderOrientDB = new LoderOrientDB();
        this.entityPostgres = new EntityPostgres();
    }


    public void importEntityFromPostgreToOrient(String yago_id){
        logger.info("[importEntityFromPostgreToOrient] importing ...");
        if( this.entityPostgres.getEntityStatus(yago_id) != 0){
            logger.info("[importEntityFromPostgreToOrient] already inserted before!");
            return;
        }
        Set<String> twoDegrees = insertTriplesOfEntity( yago_id );

        // 插入二度节点 -> 废弃
        /*
        for(String yago_id_two: twoDegrees) {
            insertTriplesOfEntity(yago_id_two);
        }
        */
        this.entityPostgres.storeEntityStatus(yago_id, 1);
    }


    private Set<String> insertTriplesOfEntity(String yago_id){
        Set<String> entities = new HashSet<>();
        List<RowYagoTriple> rows = this.extractorPostgres.getAllTripeOfEntity( yago_id );
        for(RowYagoTriple row:rows){
            this.loderOrientDB.saveTripleTuple( row );
            if(RelationLabel.yagoLabels.nonRelationLabel.contains(row.predicate) ) continue;
            entities.add( row.subject );
            entities.add( row.object );
        }
        return entities;
    }


    /***************************************************************
     *
     * @param args
     */
    public static void main(String[] args){
        if(args.length == 0){
            System.err.println("args can't be empty! please iinput at least one entity");
        }

        EntityExtractor entityExtractor = new EntityExtractor();
        for(String entity: args){
            entityExtractor.importEntityFromPostgreToOrient( entity );
            System.out.println("\n\nimported " + entity );
        }

    }

}
